<template>
  <CustomTableCard 
    footer
    temporary 
    actions 
    :total="total" 
    :page.sync="queryParams.page" 
    :limit.sync="queryParams.limit" 
    :width="1000"
    :showDrawer.sync="showDrawer" 
    @on-page="getList" 
    @cancel="handleCancel"
    @ok="handleOk"
    :title="baseInfo.id ? $t('actions.edit') : $t('actions.add')">
    <div slot="header">
      <v-row>
        <v-col cols="3">
          <v-text-field
            v-model.trim="queryParams.keyword"
            :label="$t('placeholder.keyword')"
            outlined
            dense
            hide-details
            clearable
            @keyup.enter.native="getList(1)"
          ></v-text-field>
        </v-col>
        <v-col>
          <v-btn color="info" class="mr-3" @click="getList(1)">{{ $t('actions.search') }}</v-btn>
        </v-col>
        <v-col cols="1" class="text-right">
          <v-btn color="primary" @click="showDrawer = true">{{ $t('actions.add') }}</v-btn>
        </v-col>
      </v-row>
    </div>
    <el-table
      v-loading="listLoading"
      v-auto-height
      :height="tableHeight"
      :data="tableData"
      stripe
      fit
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column
        type="selection"
        align="center"
        width="55">
      </el-table-column>
      <el-table-column
        fixed
        prop="name"
        :label="$t('organization.roleModules.field.name')">
      </el-table-column>
      <el-table-column
        prop="name_en"
        :label="$t('organization.roleModules.field.nameEn')">
      </el-table-column>
      <el-table-column
        prop="slug"
        :label="$t('organization.roleModules.field.mark')">
      </el-table-column>
      <!-- <el-table-column
        fixed="right"
        prop="status"
        :label="$t('system.fields.status')"
        width="140">
        <template slot-scope="{ row }">
          <v-switch class="mt-0" dense hide-details :input-value="row.status == 1" :label="row.status == 1 ? '已激活' : '已锁定'" @change="setStatus(row)"></v-switch>
        </template>
      </el-table-column> -->
      <el-table-column
        fixed="right"
        :label="$t('organization.roleModules.field.action')"
        align="center"
        width="180">
        <template slot-scope="{ row }">
          <v-btn class="mr-2" small color="primary" outlined @click="handleEdit(row)">{{ $t('actions.edit') }}</v-btn>
          <v-btn small color="warning" outlined @click="handleRmove(row)">{{ $t('actions.delete') }}</v-btn>
        </template>
      </el-table-column>
    </el-table>
    <div slot="actions">
      <v-btn small color="warning" :disabled="!multipleSelection.length" class="mr-2" @click="handleRmove()">{{ $t('actions.delete') }}</v-btn>
      <!-- <v-btn small color="success" :disabled="!multipleSelection.length" class="mr-2" @click="setStatusAll(1)">{{ $t('actions.open') }}</v-btn> -->
      <!-- <v-btn small color="warning" :disabled="!multipleSelection.length" @click="setStatusAll(2)">{{ $t('actions.close') }}</v-btn> -->
    </div>
    <section slot="drawer" class="pa-3">
      <v-form
        ref="form"
        :lazy-validation="false"
      >
        <v-card class="mb-4">
          <v-card-text>
            <div class="d-flex pt-2">
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>{{ $t('organization.roleModules.field.name') }}</label>
                <v-text-field
                  v-model="baseInfo.name"
                  placeholder="请输入"
                  clearable
                  dense
                  :rules="[rules.required]"
                  required
                ></v-text-field>
              </div>
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3">{{ $t('organization.roleModules.field.nameEn') }}</label>
                <v-text-field
                  v-model="baseInfo.name_en"
                  placeholder="请输入"
                  clearable
                  dense
                ></v-text-field>
              </div>
            </div>
            <div class="d-flex pt-2">
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>{{ $t('organization.roleModules.field.mark') }}</label>
                <v-text-field
                  v-model="baseInfo.slug"
                  placeholder="请输入"
                  clearable
                  dense
                  :rules="[rules.required]"
                  required
                ></v-text-field>
              </div>
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3">{{ $t('organization.roleModules.field.remark') }}</label>
                <v-text-field
                  v-model="baseInfo.describe"
                  placeholder="请输入"
                  clearable
                  dense
                ></v-text-field>
              </div>
            </div>
            <div class="d-flex align-center px-3">
              <label style="width: 140px" class="text-right pr-3"></label>
              <v-row>
                <v-col cols="6">
                  <div class="mb-4">功能权限</div>
                  <v-text-field
                    v-model="filterText"
                    label="输入关键字进行过滤"
                    flat
                    hide-details
                    outlined
                    clearable
                    dense
                    clear-icon="mdi-close-circle-outline"
                  ></v-text-field>
                  <el-tree
                    v-if="showDrawer"
                    node-key="id"
                    :data="menus"
                    :show-checkbox="true"
                    :default-checked-keys="baseInfo.menu_id"
                    :props="{
                      children: 'childs',
                      label: 'title'
                    }"
                    :filter-node-method="filterNode"
                    @check="handleClickMenu"
                    ref="tree">
                  </el-tree>
                </v-col>
                <v-col cols="6">
                  <div class="mb-4">数据权限</div>
                  <v-text-field
                    v-model="filterDataText"
                    label="输入关键字进行过滤"
                    flat
                    hide-details
                    outlined
                    clearable
                    dense
                    clear-icon="mdi-close-circle-outline"
                  ></v-text-field>
                  <el-tree
                    v-if="showDrawer"
                    node-key="id"
                    :data="deptList"
                    :show-checkbox="true"
                    :default-checked-keys="baseInfo.department_id"
                    :props="{
                      children: 'childs',
                      label: 'name'
                    }"
                    :filter-node-method="filterNode"
                    @check="handleClickDept"
                    ref="treedata">
                  </el-tree>
                </v-col>
              </v-row>
            </div>
          </v-card-text>
        </v-card>
      </v-form>
    </section>
  </CustomTableCard>
</template>

<script>
// @ is an alias to /src
import { mapState } from 'vuex'
import { getRoleList, deleteRole, createRole, updateRole } from '@/api/organization'
import mixin from './mixin'

export default {
  name: 'role',
  mixins: [mixin],
  created() {
    if (!this.deptList.length) {
      this.$store.dispatch('organization/getDeptList', {page: 1, limit: 500})
    }
    if (!this.menus.length) {
      this.$store.dispatch('organization/getMenus')
    }
    this.getList()
    this.cloneFormData()
  },
  activated() {
    console.log('activated')
    this.getList()
  },
  deactivated() {
    console.log('deactivated')
  },
  computed: {
    ...mapState('organization', ['deptList', 'menus'])
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterDataText(val) {
      this.$refs.treedata.filter(val);
    }
  },
  data() {
    return {
      tableHeight: 500,
      showDrawer: false,
      tableData: [{}],
      total: 0,
      listLoading: false,
      queryParams: {
        page: 1,
        limit: 20,
        keyword: '',
      },

      baseInfo: {
        id: undefined,
        name: '',
        name_en: '',
        slug: '',
        describe: '',
        department_id: [],
        menu_id: []
      },

      filterText: '',
      filterDataText: '',

      multipleSelection: [],

      rules: {
        required: value => !!value || 'required',
      }
    }
  },

  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.name ? data.name.indexOf(value) !== -1 : data.title.indexOf(value) !== -1
    },
    handleClickDept(data, { checkedKeys }) {
      this.baseInfo.department_id = checkedKeys
    },
    handleClickMenu(data, { checkedKeys }) {
      this.baseInfo.menu_id = checkedKeys
    },
    // 克隆数据 用于重置数据使用
    cloneFormData() {
      this._baseInfo = Object.assign({}, this.baseInfo)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取列表
    getList(page) {
      if (/\d+/.test(page)) {
        this.queryParams.page = page
      }
      this.listLoading = true
      getRoleList(this.queryParams).then(response => {
        this.tableData = response.data.data
        this.total = response.data.count
      }).finally(() => {
        this.listLoading = false
      })
    },
    // 编辑列表
    handleEdit(row) {
      this.showDrawer = true
      Object.assign(this.baseInfo, row)
    },
    // 删除列表
    handleRmove(row) {
      let ids = []
      if (row) {
        ids = [row.id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      this.$confirm(this.$t('tips.delete'), this.$t('other.tip'), {
        center: true,
        type: 'warning'
      }).then(() => {
        deleteRole({id: [row.id]}).then(() => {
          this.$message.success('success')
          this.getList()
        })
      })
    },
    // // 批量设置状态
    // setStatusAll(status) {
    //   let ids = this.multipleSelection.map(item => item.id)
    //   this.updateStatus({id: ids, status})
    // },
    // // 设置状态
    // setStatus(row) {
    //   let status = row.status == 1 ? 2 : 1
    //   this.updateStatus({id: [row.id], status})
    // },
    // // 更新状态
    // updateStatus(params) {
    //   systemApi.changeStatus(params).then(() => {
    //     this.$message.success('success')
    //     this.getList()
    //   })
    // },
    // 右侧窗口关闭事件
    handleCancel() {
      this.resetForm()
    },
    // 重置表达数据和验证
    resetForm () {
      Object.assign(this.baseInfo, this._baseInfo)
      this.$refs.form.resetValidation()
    },
    // 右侧窗口确定事件
    handleOk() {
      // console.log(this.baseInfo)
      if(this.$refs.form.validate()) {
        if(this.baseInfo.id) {
          updateRole(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList()
            this.showDrawer = false
          })
        } else {
          createRole(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList(1)
            this.showDrawer = false
          })
        }
      }
    }
  }
}
</script>
